/**
 * load gateways that belong to an account.
 */

var errorCodes = require("../ErrorCode/errCode.js");
var accountTable = require("../Redis/accountTable.js");
var redis = require("../Redis/redis.js");
var gatewayTable = require("../Redis/gatewayTable.js");

function replyTo(context) {
	"use strict";
	var res = context.res;
	var groups = context.groups;
	
	res.writeHead(200);
	res.end(JSON.stringify(groups));
}

function loadGatewayWith(context) {
	"use strict";
	var res = context.res;
	var gatewayIds = context.gatewayIds;
	
	var groupscb = function(err, replies) {
		if (err) {
			console.error("loadGroup error:" + err);
		} else {
			if (replies) {
				for(var k in replies) {
					if (replies.hasOwnProperty(k)) {
						var r = replies[k];
						var group = JSON.parse(r);
						context.groups.push(group);
					}
				}
			} else {
				console.error("load group error, group not exist");
			}
		}
	};
	
	context.beginMulti();
	
	gatewayIds.forEach(function(gwId){
		gatewayTable.loadAllGroups(context, gwId, groupscb);
	});
	
	context.endMulti(function(err) {
		if (err) {
			errorCodes.errorEnd(errorCodes.ERR_DATABASE, ""+err, res);
		} else {
			replyTo(context);
		}
	});
}

function loadGatewayHandler(req, res, account) {
	"use strict";
	var context = {};
	context.gateways = [];
	context.res = res;
	
	redis.setClient(context);
	
	accountTable.loadFields(context, account, ["gateways"], function(err, replies){
		if (err) {
			errorCodes.errorEnd(errorCodes.ERR_DATABASE, ""+err, res);
		} else {
			var gatewayIds = null;
			var jgatewayIds = replies[0];
			if (!jgatewayIds) {
				gatewayIds = JSON.parse(jgatewayIds);
			}
			
			if (!gatewayIds || gatewayIds.length < 1) {
				replyTo(context);
				return;
			}
			
			context.gatewayIds = gatewayIds;
			loadGatewayWith(context);
		}
	});
}

module.exports = loadGatewayHandler;
